#! /bin/sh

source /etc/rc.d/common

SSHD="/usr/sbin/sshd"
SSHD_LOCK="/var/lock/sshd"
DFLT_OPTS="-f /etc/ssh/sshd_config"

check_args ${@}

SCRIPT="$(/usr/bin/basename ${0})"
if check_opts_set ${SCRIPT}; then
    USER_OPTS="$(get_rc_opts ${SCRIPT})"
    if [ ${?} -ne 0 ]; then
        /bin/echo ${USER_OPTS}
        exit 1
    fi
else
    USER_OPTS="${DFLT_OPTS}"
fi

start() {
    # Generate keys if necessary
    for i in ed25519 ecdsa dsa rsa; do
        key_file="/etc/ssh/ssh_host_${i}_key"
        if [ ! -e "${key_file}" ]; then
            /bin/echo "Generating ${i} host key..."
            /usr/bin/ssh-keygen -t ${i} -f "${key_file}" -N ''
        fi
    done
    # Start sshd
    /bin/echo "Starting sshd..."
    eval ${SSHD} ${USER_OPTS} || exit 1
    /bin/touch ${SSHD_LOCK}
}

stop() {
    /bin/echo "Stopping sshd..."
    /bin/kill -TERM $(/bin/pidof ${SSHD}) || exit 1
    wait_for_stop ${SSHD} && /bin/rm -f ${SSHD_LOCK}
}

status() {
    /bin/pidof ${SSHD} > /dev/null 2>&1
    exit ${?}
}

# Perform specified action
${1}
